package com.leexuan.ordersystem.actions;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

import com.leexuan.ordersystem.beans.Deliver;
import com.leexuan.ordersystem.db.DeliverDB;
import com.leexuan.ordersystem.db.OrderDB;
import com.leexuan.ordersystem.db.ProductDB;
import com.leexuan.ordersystem.forms.DeliverForm;

public class AddDeliverAction extends Action {

	public AddDeliverAction() {
		super();
	}

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {

		DeliverForm fm = (DeliverForm) form;

		Deliver st = new Deliver();

		st.setOdid(fm.getOdid());
		st.setOid(fm.getOid());
		st.setQuantity(fm.getQuantity());

		Date date = new Date();

		SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy-MM-dd");

		st.setDate(bartDateFormat.format(date));

		DeliverDB db = new DeliverDB();

		OrderDB odb = new OrderDB();

		ProductDB pdb = new ProductDB();

		try {

			pdb.getConnection();

			if (pdb.getProductNum(fm.getPid()) < fm.getQuantity()) {

				ActionErrors errors = new ActionErrors();
				errors.add("notEnoughProductNum", new ActionMessage(
						"error.product.notEnoughProductNum"));
				saveErrors(request, errors);

				HttpSession session = request.getSession();
				session.setAttribute("deliveroid", Integer.toString(fm.getOid()));

				return mapping.findForward("failure");

			}

			if (fm.getQuantity() > fm.getRemain()) {

				ActionErrors errors = new ActionErrors();
				errors.add("OverDeliverNum", new ActionMessage("error.product.OverDeliverNum"));
				saveErrors(request, errors);

				HttpSession session = request.getSession();
				session.setAttribute("deliveroid", Integer.toString(fm.getOid()));

				return mapping.findForward("failure");

			}

			pdb.getConnection();

			pdb.subProductNum(fm.getQuantity(), fm.getPid());

			db.getConnection();

			db.addDeliver(st);

			odb.getConnection();
			odb.subOrderDetail(fm.getQuantity(), fm.getOdid());

			HttpSession session = request.getSession();
			session.setAttribute("deliveroid", Integer.toString(fm.getOid()));

			return mapping.findForward("success");

		} catch (Exception e) {

			return (new ActionForward(mapping.getInput()));
		} finally {
			try {
				db.closeConnection();
				odb.closeConnection();
				pdb.closeConnection();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

}
